package controller;

import gui.LoginGUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import model.User;

import client.LoginClient;

public class LoginAction implements ActionListener {

	private LoginGUI gui;
	private LoginClient client;

	public LoginAction(LoginGUI gui, LoginClient client) {
		this.gui = gui;
		this.client = client;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (!isEmpty())
			doLogin();
		else
			JOptionPane.showMessageDialog(null, "The fields cannot be empty",
					"Message", JOptionPane.ERROR_MESSAGE);
	}

	private boolean isEmpty() {
		if (gui.getTf_username().getText().equals("")
				|| new String(gui.getTf_password().getPassword()).equals(""))
			return true;
		return false;
	}

	private void doLogin() {
		String username = gui.getTf_username().getText();
		String password = new String(gui.getTf_password().getPassword());
		User user = client.getUser(username, password);

		if (user != null) {
			gui.getTa_detail().setText(user.toString());
		} else {
			gui.getTa_detail()
					.setText("Error: username or password is invalid");
		}
	}

}
